package com.ctrlcar.giftrecord.interceptors;


import com.ctrlcar.giftrecord.utils.JwtUtil;
import com.ctrlcar.giftrecord.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author:
 * @Description: 将获得的token解析出来，保存到ThreadLocal中
 * @DateTime: 2024/10/9 15:47
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("---------------登录拦截器 LoginInterceptor 执行了---------------");
        //1.获取请求头中的token
        String strUserToken = request.getHeader("Authorization");
        //3.判断用户是否存在
        if (strUserToken == null){
            //4.不存在拦截
            System.out.println("-----------拦截了 401 ------------");
            response.setStatus(401);
            return false;
        }

        //5.存在 保存用户信息（先解析token）到ThreadLocal
        Map<String, Object> tokenMap = JwtUtil.parseToken(strUserToken);
        ThreadLocalUtil.set(tokenMap);
//        UserHolder.saveUser((UserDTO) user);
        //6.放行
        return true;
    }
}
